package cn.tedu.lbs.basic.web.service;

import cn.tedu.lbs.basic.web.repository.UserRepository;
import cn.tedu.lbs.basic.web.utils.AuthenticationContextUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.common.basic.util.RandomUserName;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.pojo.basic.dto.UserDTO;
import com.tarena.lbs.pojo.basic.param.UserParam;
import com.tarena.lbs.pojo.basic.po.UserPO;
import com.tarena.lbs.pojo.basic.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public void register(UserParam userParam) throws BusinessException {
        //1.检查手机号重复
        checkPhoneReuse(userParam.getPhone());
        //2.新增创建
        save(userParam);
    }
    private void save(UserParam userParam){
        //将param转化po 缺少属性补充一下 phone password
        UserPO poParam = new UserPO();
        BeanUtils.copyProperties(userParam,poParam);
        //1.状态status 初始化0 表示么有绑定过标签 如果是1 就是绑过
        poParam.setStatus(0);
        //2.nickname username 随机给老钱 大钱 小钱
        poParam.setNickName(RandomUserName.createRandomName());
        poParam.setUserName(RandomUserName.createRandomName());
        //3.regTime入住时间
        poParam.setRegTime(new Date());
        //调用仓储层save
        userRepository.save(poParam);
    }

    private void checkPhoneReuse(String phone) throws BusinessException {
        //select count(*) from lbs_user where phone=#{phone}
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("phone",phone);
        long count = userRepository.count(queryWrapper);
        Asserts.isTrue(count>0,new BusinessException("-2","手机号重复"));
    }
    public UserDTO detail(Integer userId) throws BusinessException {
        //2.读取userPO
        UserPO userPO = userRepository.getById(userId);
        //3.转化vo返回
        UserDTO userDto = new UserDTO();
        BeanUtils.copyProperties(userPO,userDto);
        return userDto;
    }
    public UserVO detail() throws BusinessException {
        //1.从认证获取userId
        Integer userId=getUserId();
        //2.读取userPO
        UserPO userPO = userRepository.getById(userId);
        //3.转化vo返回
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userPO,userVO);
        return userVO;
    }
    private Integer getUserId() throws BusinessException {
        //读取 认证 传递的userPrinciple 线程和过滤器线程相同
        UserPrinciple userPrinciple = AuthenticationContextUtil.get();
        Asserts.isTrue(userPrinciple==null,new BusinessException("-2","用户认证解析失败"));
        return userPrinciple.getId();
    }
}
